﻿using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(MonoBehaviour),true)]
public class MyMonoBehaviourEditor : Editor
{
    const string monoscript = "PPtr<MonoScript>";

    public override void OnInspectorGUI()
    {
        if(!(WhoReferencedWindow.IsEnable() && WhoReferencedWindow.Contains(target as Component)))
        {
            base.OnInspectorGUI();
            return;
        }

        serializedObject.Update();
        var serializedProperty = serializedObject.GetIterator();
        serializedProperty.Next(true);

        while (serializedProperty.NextVisible(serializedProperty.isExpanded))
        {
            EditorGUI.indentLevel = serializedProperty.depth;
            if (!serializedProperty.hasVisibleChildren)
            {
                DrawPropertyField(serializedProperty);
            }
            else
            {
                DrawFoldout(serializedProperty);
            }
        }

        serializedObject.ApplyModifiedProperties();
    }

    void DrawFoldout(SerializedProperty serializedProperty)
    {
        var rect = GetControlRect(serializedProperty);
        serializedProperty.isExpanded = EditorGUI.Foldout(new Rect(rect.x, rect.y + rect.height - 16, rect.width, 16), serializedProperty.isExpanded, serializedProperty.name,true);
    }

    void DrawPropertyField(SerializedProperty serializedProperty)
    {
        var rect = GetControlRect(serializedProperty);
        DrawHighlight(serializedProperty, rect);
        ScriptImmutable(serializedProperty);

        EditorGUI.PropertyField(rect, serializedProperty);
        GUI.enabled = true;
    }

    Rect GetControlRect(SerializedProperty serializedProperty)
    {
#if UNITY_5
        var height = EditorGUI.GetPropertyHeight(serializedProperty,null, false);
#else
        var height = EditorGUI.GetPropertyHeight(serializedProperty, false);
#endif
        return EditorGUILayout.GetControlRect(GUILayout.MinHeight(height));
    }

    void ScriptImmutable(SerializedProperty serializedProperty)
    {
        if (serializedProperty.type == monoscript)
        {
            GUI.enabled = false;
        }
    }

    void DrawHighlight(SerializedProperty serializedProperty,Rect rect)
    {
        if (WhoReferencedWindow.Contains(serializedProperty))
        {
            EditorGUI.DrawRect(new Rect(0, rect.y + rect.height - 16, rect.width, 16), new Color(0.5f, 0.5f, 0, 1f));
        }
    }
}
